﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp.TestFunc.代码备份
{
    public static class Example_Mutex
    {
        private static Mutex mutex = new Mutex(); // 创建无名称的 Mutex
        private static int counter = 0;

        public static void Run()
        {
            Thread t1 = new Thread(Increment);
            Thread t2 = new Thread(Increment);

            t1.Start();
            t2.Start();

            t1.Join();
            t2.Join();

            Console.WriteLine("Final counter value: " + counter);
        }

        static void Increment()
        {
            for (int i = 0; i < 1000; i++)
            {
                mutex.WaitOne(); // 获取锁
                counter++;       // 临界区（共享资源）
                mutex.ReleaseMutex(); // 释放锁
            }
        }

    }

}
